package com.noble.library.permission;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import com.noble.library.R;
import com.noble.library.log.PSP;
import com.noble.library.log.PToast;
import com.noble.library.observe.MsgMgr;
import com.noble.library.permission.andPermission.AndPermission;
import com.noble.library.permission.andPermission.Permission;
import com.noble.library.permission.callback.PermissionListener;
import com.noble.library.permission.rationale.InstallRationale;
import com.noble.library.permission.rationale.RuntimeRationale;

import java.io.File;
import java.util.List;

/**
 * Android.M 权限管理
 */
public class PermissionUtil {
    // ==============================   相机，麦克风权限  =============================================
    private static final String CHECK_AV_AUTH = "av_auth";

    private static void resetAVAuth(boolean auth) {
        PSP.getInstance().put(CHECK_AV_AUTH, auth);
    }

    public static boolean getAVAuth() {
        return PSP.getInstance().getBoolean(CHECK_AV_AUTH, false);
    }

    /**
     * 音视频权限
     */
    public static void checkAVPermission(Context context, final PermissionListener listener) {
        boolean permission = getAVAuth();
        if (permission) {
            if (listener != null)
                listener.success();
            return;
        }
        requestPermission(context, new PermissionCallback() {
            @Override
            public void onSuccess() {
                resetAVAuth(true);
                if (listener != null)
                    listener.success();
            }

            @Override
            public void onDenied() {
                if (listener != null)
                    listener.fail();
            }
        }, Permission.CAMERA, Permission.RECORD_AUDIO);
    }

    // ==============================   读写文件权限  =============================================
    private static final String CHECK_STORAGE_AUTH = "storage_auth";

    private static void resetStorageAuth(boolean auth) {
        PSP.getInstance().put(CHECK_STORAGE_AUTH, auth);
    }

    private static boolean getStorageAuth() {
        return PSP.getInstance().getBoolean(CHECK_STORAGE_AUTH, false);
    }

    /**
     * 读写文件权限
     */
    public static void checkStoragePermission(Context context, final PermissionListener listener) {
        boolean permission = getStorageAuth();
        if (permission) {
            if (listener != null)
                listener.success();
            return;
        }
        requestPermission(context, new PermissionCallback() {
            @Override
            public void onSuccess() {
                resetStorageAuth(true);
                if (listener != null)
                    listener.success();
            }

            @Override
            public void onDenied() {
                if (listener != null)
                    listener.fail();
            }
        }, Permission.Group.STORAGE);
    }

    // =================================================  授权 ==================================

    /**
     * 请求权限：程序内可直接授权
     */
    public static void requestPermission(final Context context, final PermissionCallback callback, String... permissions) {
        AndPermission.with(context)
                .runtime()
                .permission(permissions)
                .rationale(new RuntimeRationale())
                .onGranted(permissions1 -> {
                    if (callback != null)
                        callback.onSuccess();
                })
                .onDenied(permissions12 -> {
                    if (callback != null)
                        callback.onDenied();
                    PToast.showShort(R.string.permission_failure);
                    try {
                        if (AndPermission.hasAlwaysDeniedPermission(context, permissions12)) {
                            showSettingDialog(context, permissions12);
                        }
                    } catch (Exception e) {
                    }
                })
                .start();
    }

    /**
     * 安装程序权限： 即存储卡读写权限
     */
    public static void requestPermissionForInstallPackage(final Context context, final String filePath) {
        AndPermission.with(context)
                .runtime()
                .permission(Permission.Group.STORAGE)
                .rationale(new RuntimeRationale())
                .onGranted(data -> installPackage(context, filePath))
                .onDenied(data -> PToast.showShort("手机已拒绝安装外部应用"))
                .start();
    }

    /**
     * 授权完成回调
     */
    public interface PermissionCallback {
        void onSuccess();

        void onDenied();
    }

    // =========== 内部工具接口 ====================

    /**
     * App内未能成功授权，提示到手机设置页手动进行授权
     */
    private static void showSettingDialog(final Context context, final List<String> permissions) {
        MsgMgr.getInstance().runOnUiThread(() -> {
            List<String> permissionNames = Permission.transformText(context, permissions);
            String message = context.getString(R.string.permission_always_failed, TextUtils.join("\n", permissionNames));

            new AlertDialog.Builder(context)
                    .setCancelable(false)
                    .setTitle(R.string.tip)
                    .setMessage(message)
                    .setPositiveButton(R.string.ok, (dialog, which) -> setPermission(context))
                    .setNegativeButton(R.string.cancel, (dialog, which) -> {
                    })
                    .show();
        });
    }

    /**
     * 直接打开应用系统授权页面
     */
    private static void setPermission(Context context) {
        AndPermission.with(context)
                .runtime()
                .setting()
                .onComeback(() -> {
                    // 授权页面返回回调
                })
                .start();
    }

    /**
     * 安装应用
     */
    private static void installPackage(Context context, String filePath) {
        AndPermission.with(context)
                .install()
                .file(new File(filePath))
                .rationale(new InstallRationale())
                .onGranted(data -> {
                    // Installing.
                })
                .onDenied(data -> {
                    // The user refused to install.
                })
                .start();
    }
}
